package cx.v1.util;

import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD2Digest;
import org.bouncycastle.crypto.digests.MD4Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;

public class Digestion {
    
    public Digestion() {
    }
    
    public byte[] getDigestion(String string) throws Exception
    {     
        return this.getDigestion(string, null, null);
    }
    
    public byte[] getDigestion(String string, String algoritmo) throws Exception
    {
        return this.getDigestion(string, algoritmo, null);
    }
    
    public byte[] getDigestion(String cadenaOriginal, String algoritmo, String encodign) throws Exception
    {       
        try
        {
            Digest digest = null;
            if(algoritmo != null){
            if(algoritmo.equals("MD2")) digest = new MD2Digest();
            else if (algoritmo.equals("MD4")) digest = new MD4Digest();
            else if (algoritmo.equals("MD5")) digest = new MD5Digest();
            else if (algoritmo.equals("SHA-1")) digest = new SHA1Digest();
            else throw new Exception("Se present� un error al intentar reconocer el algoritmo");
            }
            else{
                digest = new MD5Digest();
            }
            byte[] cadenaCifrada = new byte[digest.getDigestSize()]; 
		
            byte[] cadenaOriginalEncodign = null;
            
            if(encodign != null)
            {
                cadenaOriginalEncodign = cadenaOriginal.getBytes(encodign);
            }
            else
            {
                cadenaOriginalEncodign = cadenaOriginal.getBytes();
            }
            
            digest.update(cadenaOriginalEncodign, 0, cadenaOriginalEncodign.length);						
            digest.doFinal(cadenaCifrada,0);
		
            return cadenaCifrada;
        }
        catch(Exception ex)
        {
            throw new Exception("La digesti�n de la cadena original no fue generada");
        }
    }
    
}
